package com.fbt.transfer.app.driver.ui.settings;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;
import com.fbt.transfer.app.driver.BuildConfig;
import com.fbt.transfer.app.driver.activity.BaseActivity;
import com.fbt.transfer.app.driver.activity.LoginActivity;
import com.fbt.transfer.app.driver.databinding.ActivitySettingsBinding;
import com.fbt.transfer.app.driver.http.AbstractCallback;
import com.fbt.transfer.app.driver.model.Result;
import com.fbt.transfer.app.driver.util.PermissionUtils;
import com.fbt.transfer.app.driver.util.UserManager;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;

public class SettingsActivity extends BaseActivity {

  public static final String TAG = "SettingsActivity";
  private AudioManager audioManager = null;
  private ActivitySettingsBinding activitySettingsBinding = null;

  @Override
  protected void initView () {
    activitySettingsBinding = ActivitySettingsBinding.inflate(getLayoutInflater());
    setContentView(activitySettingsBinding.getRoot());
    // 初始化AudioManager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // 设置标题
    setTitle("设置");

    // 初始化音量控制
    initVolumeControl();

    // 初始化悬浮窗开关
    initFloatingWindowSwitch();

    // 初始化环境切换选项
    initEnvironmentSwitch();
  }

  private void initVolumeControl () {

    // 获取最大音量
    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    activitySettingsBinding.volumeSeekbar.setMax(maxVolume);

    // 获取当前音量
    int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    activitySettingsBinding.volumeSeekbar.setProgress(currentVolume);

    // 设置音量变化监听器
    activitySettingsBinding.volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
          audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
        }
      }

      @Override
      public void onStartTrackingTouch (SeekBar seekBar) {
      }

      @Override
      public void onStopTrackingTouch (SeekBar seekBar) {
      }
    });
  }

  private void initFloatingWindowSwitch () {

    // 检查是否有悬浮窗权限
    boolean hasPermission = PermissionUtils.hasOverlayPermission(this);
    activitySettingsBinding.floatingWindowSwitch.setChecked(hasPermission);

    activitySettingsBinding.floatingWindowSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
      if (isChecked) {
        // 如果用户想要开启悬浮窗但没有权限，跳转到设置页面
        if (!PermissionUtils.hasOverlayPermission(this)) {
          Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
          startActivity(intent);
          Toast.makeText(this, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show();
          // 重置开关状态
          buttonView.setChecked(false);
        }
      } else {
        // 用户关闭悬浮窗权限，执行撤销权限操作
        revokeOverlayPermission();
      }
    });
  }

  // 撤销悬浮窗权限
  private void revokeOverlayPermission () {
    // 这里可以执行关闭悬浮窗相关的逻辑，例如停止相关服务
    // 如果需要提示用户，可以添加Toast或其他UI反馈
    Toast.makeText(this, "已关闭悬浮窗权限", Toast.LENGTH_SHORT).show();
    // 可以在这里添加其他撤销权限后的处理逻辑
  }

  public void startServiceMinimap () {
    // 判断是否有悬浮窗权限
    if (PermissionUtils.hasOverlayPermission(this)) {
      Log.d(TAG, "悬浮窗权限已授予");
      // 权限已授予，可以启动悬浮窗服务
    } else {
      // 检查是否已经请求过悬浮窗权限
      if (!PermissionUtils.hasRequestedOverlayPermission(this)) {
        Log.d(TAG, "悬浮窗权限未授予，准备跳转设置");
        // 标记已请求过悬浮窗权限
        PermissionUtils.markOverlayPermissionRequested(this);
        jumpToPermission();
      } else {
        // 已经请求过权限，但用户拒绝了，不再重复请求
        Log.d(TAG, "悬浮窗权限已请求过但未授予，不再重复请求");
      }
    }
  }

  // 跳转系统设置-悬浮窗页面
  public void jumpToPermission () {
    Intent intent = new Intent(
        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
        Uri.parse("package:" + getApplicationContext().getPackageName())
    );
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getApplicationContext().startActivity(intent);
  }


  private void initEnvironmentSwitch () {
    // 只在debug模式下显示环境切换选项
    if (BuildConfig.DEBUG) {
      activitySettingsBinding.llEnvironmentSwitch.setVisibility(View.VISIBLE);
      updateEnvironmentStatus();

      activitySettingsBinding.llEnvironmentSwitch.setOnClickListener(v -> showEnvironmentSwitchDialog());
    }
  }

  private void updateEnvironmentStatus () {
    boolean isTestEnv = UserManager.getInstance(this).isTestEnvironment();
    activitySettingsBinding.tvCurrentEnvironment.setText("当前环境：" + (isTestEnv ? "测试环境" : "生产环境"));
  }

  private void showEnvironmentSwitchDialog () {
    boolean isTestEnv = UserManager.getInstance(this).isTestEnvironment();
    String[] environments = {"测试环境", "生产环境"};
    int currentChoice = isTestEnv ? 0 : 1;

    new AlertDialog.Builder(this)
        .setTitle("选择环境")
        .setSingleChoiceItems(environments, currentChoice, (dialog, which) -> {
          if ((which == 0) != isTestEnv) {
            // 环境发生变化
            switchEnvironment(which == 0);
          }
          dialog.dismiss();
        })
        .setNegativeButton("取消", null)
        .show();
  }

  private void switchEnvironment (boolean toTestEnv) {
    new AlertDialog.Builder(this)
        .setTitle("切换环境")
        .setMessage("切换环境需要重新登录，是否继续？")
        .setPositiveButton("确定", (dialog, which) -> {
          // 设置新环境
          UserManager.getInstance(SettingsActivity.this).setEnvironment(toTestEnv);

          // 调用登出接口
          apiInterface.logout().enqueue(new AbstractCallback<Boolean>(this, false) {
            @Override
            protected void onSuccess (Boolean data) {
              // 清除本地用户数据
              restartAppAndLogin();
            }

            @Override
            public void onFailure (@NotNull Call<Result<Boolean>> call, Throwable t) {
              restartAppAndLogin();
            }

            private void restartAppAndLogin () {
              // 清除本地用户数据
              UserManager.getInstance(SettingsActivity.this).clearUserInfo();
              // 重启应用进入登录页面
              // 创建新的 Intent 跳转到 LoginActivity
              Intent intent = new Intent(SettingsActivity.this, LoginActivity.class);
              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // 清除任务栈
              startActivity(intent);
              // 结束当前 Activity
              finish();
            }


          });
        })
        .setNegativeButton("取消", null)
        .show();
  }
}